const header = document.querySelector(".header")
const nav = document.querySelector(".nav")
const ul = document.querySelector(".nav-menu")
const navHeight = nav.getBoundingClientRect().height // 64px
const stickyNav = (entries) => {
  const [entry] = entries

  if (!entry.isIntersecting) nav.classList.add("header-sticky")
  else nav.classList.remove("header-sticky")
}
const headerObserver = new IntersectionObserver(stickyNav, {
  root: null,
  threshold: 0,
  rootMargin: `${navHeight}px`,
})
headerObserver.observe(header)


// 点击下滑
const sections = document.querySelectorAll("section")

ul.addEventListener("click", (e) => {
  e.preventDefault()

  if (e.target.classList.contains("nav-link")) {
    const id = e.target.getAttribute("href")
    document.querySelector(id).scrollIntoView({ behavior: "smooth" })
    sections.forEach((section) => (section.style.paddingTop = "100px"))
  }
})

// 淡出显示
const allSections = document.querySelectorAll(".section")

const fadingSection = (entries, observer) => {
  const [entry] = entries
  if (!entry.isIntersecting) return
  entry.target.classList.remove("section-hidden")
  observer.unobserve(entry.target)
}

const sectionObserver = new IntersectionObserver(fadingSection, {
  root: null,
  threshold: 0.12,
})

allSections.forEach((section) => {
  sectionObserver.observe(section)
  section.classList.add("section-hidden")
})

// 显示菜单
const mobileMenu = document.querySelector(".mobile-menu")
const overlay = document.querySelector(".navigation")

const showMenu = () => {
  overlay.classList.add("show-menu")
}

const hideMenu = () => {
  overlay.classList.remove("show-menu")
}

mobileMenu.addEventListener("click", showMenu)
overlay.addEventListener("click", hideMenu)

// 点击激活导航
const navLinks = document.querySelectorAll('.nav-link')
navLinks.forEach(item => {
  item.addEventListener('click', function () {
    navLinks.forEach(link => link.classList.remove('active-link'))
    this.classList.add('active-link')
  })
})

// 滚动 sections 链接高亮 属性选择器
const sectionList = document.querySelectorAll('section[id]')
function scrollActive() {
  // 只读属性
  const scrollY = window.pageYOffset
  sectionList.forEach(current => {
    const sectionHeight = current.offsetHeight
    const sectionTop = current.offsetTop - 100
    const sectionId = current.getAttribute('id')
    if (scrollY > sectionTop && scrollY <= sectionTop + sectionHeight) {
      document.querySelector('.nav-menu a[href*=' + sectionId + ']').classList.add('active-link')
    } else {
      document.querySelector('.nav-menu a[href*=' + sectionId + ']').classList.remove('active-link')
    }
  })
}
window.addEventListener('scroll', scrollActive)